//
//  VPaiCtrl.swift
//  VPai
//
//  Created by devel on 16/9/9.
//  Copyright © 2016年 viatech. All rights reserved.
//

import UIKit




class VPaiCtrl: UIViewController{
    
    private static let TAG = "VPaiCtrl"
    
    //var mediaSource: MediaSource!

 
    var countdownButton: UIBarButtonItem = UIBarButtonItem()
    var settingButton: UIBarButtonItem = UIBarButtonItem()
    var remoteFile: UIButton = UIButton()
    var changeMode: UIButton = UIButton()
    var middleButton: UIButton = UIButton()
    var liveButton: UIBarButtonItem = UIBarButtonItem()
    var containnerView: UIView = UIView()
    
    var applicationDidEnterBackgroundObserver:AnyObject? = nil
    
    private var countDown = 0
    private var timer: NSTimer?
    private var activity = false
    private var recording = false //是否正在录像
    private var currentView: UIView?
    private var cameraView: WMCameraView = WMCameraView()
    private var vpaiMediaWebSocketEvent : VPaiMediaWebSocketEvents?
    private var vpaiCtrlWebSocketEvent : VPaiCtrlWebSocketEvents?
   
 //   private var yuvCallback : YUV420PTextureCallback?
    private var pixelBuffers = [CVPixelBufferRef]()
  //  private var decoder = H264Decoder()
    private let decoderQueue: NSOperationQueue = {
        let _queue = NSOperationQueue()
        _queue.name = "h264.decoder"
        _queue.maxConcurrentOperationCount = 1
        return _queue
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.grayColor();
        
        // 调试
        VPaiMediaWebSocket.shareInstance.openWebSocket("ws://192.168.5.1:8720/Vpaimedia")
        
        
        
        
        
        cameraView.frame = self.view.bounds;
        self.view.addSubview(cameraView)
        
        // Do any additional setup after loading the view.
        
        updateButtonImages()
        


        
      //  VPaiConnectionManager.shareInstance.registerListener(self)
        vpaiMediaWebSocketEvent = VPaiMediaWebSocket.shareInstance.registerEvent()
        vpaiMediaWebSocketEvent?.onStartRec = onStartRec
        vpaiMediaWebSocketEvent?.onStopRec  = onStopRec
        vpaiMediaWebSocketEvent?.onStartPrev = onStartPrev
        
        vpaiCtrlWebSocketEvent = VPaiCtrlWebSocket.shareInstance.registerEvent()
        vpaiCtrlWebSocketEvent?.onDeviceInfo = onDeviceInfo
        
        let notificationCenter = NSNotificationCenter.defaultCenter()
        let operationQueue = NSOperationQueue.mainQueue()
        
        weak var weakself = self
        applicationDidEnterBackgroundObserver =
            notificationCenter.addObserverForName(UIApplicationDidEnterBackgroundNotification,
                                                  object: nil, queue: operationQueue, usingBlock: {
                                                    (notification: NSNotification!) in
                                                    if weakself != nil {
                                                        weakself?.stopPrev()                                                    }
            })
        
        //LocalSetting.shareInstance.resistLocalSettingListener(self)
        
        cameraView.createPreviewController(self)
        
        //initYoutube()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VPaiCtrl.applicationDidBecomeActiveNotification(_:)), name: UIApplicationDidBecomeActiveNotification,
                                                         object: UIApplication.sharedApplication())
    }
    
    deinit{
      
    }
       override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        activity = true
        if let _ = VPaiConnectionManager.shareInstance.currentConnectVPai{
            startPrev()
        }
        remoteFile.layer.masksToBounds = true
        remoteFile.layer.cornerRadius = remoteFile.frame.size.width/2
        changeMode.layer.masksToBounds = true
        changeMode.layer.cornerRadius = changeMode.frame.size.width/2
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        activity = false
        stopPrev()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
   
    
    
   
    func enable() {
        self.changeMode.enabled = true
    }
    

    
    func countDownShot(timer : NSTimer?){
        countDown -= 1
        changeMode.setTitle("\(countDown)", forState: .Normal)
        
        if countDown <= 0 {
            self.timer?.invalidate()
            self.timer = nil
            
            changeMode.setImage(UIImage(named: "photo"), forState: .Normal)
          //  self.changeModeClick(UIButton)

        }
    }
   
    

    //点击了连接按钮
    func onConnectClick(){
        if let url = NSURL(string : "prefs:root=WIFI"){
            UIApplication.sharedApplication().openURL(url)
        }else {
           // Log.error(VPaiCtrl.TAG, msg: "onConnectClick error,can not go wifi settting")
        }
    }
    
    

    
    func onConnectedDevice(device : VPaiDevice){
        changeCurrentView(cameraView)
        if activity {
            startPrev()
        }
        settingButton.enabled = true
        countdownButton.enabled = true
        weak var weakself = self
        
        VPaiCtrlWebSocket.shareInstance.getDeviceInfo() {args in
            if args.ret == 0 {
                let info = VPaiDeviceInfo.parseFromJson(args.json)
               // weakself?.onDeviceInfo(info)
                
            }
        }
    }
    

    /// 是否隐藏倒计时按钮
    func isHideCountdownButton(isHide: Bool) {
        var barBtnArray = self.navigationItem.rightBarButtonItems
        if isHide { // 隐藏
            barBtnArray![1].enabled = false
            barBtnArray![1].tintColor = UIColor(red: 0.09, green: 0.11, blue: 0.125, alpha: 1)
            } else { // 显示
            barBtnArray![1].enabled = true
            barBtnArray![1].tintColor = UIColor.whiteColor()
        }
        
        self.navigationItem.setRightBarButtonItems(barBtnArray, animated: true)
    }
    
    func applicationDidBecomeActiveNotification(aNotification: NSNotification) {
        if activity {
            if let _ = VPaiConnectionManager.shareInstance.currentConnectVPai{
                startPrev()
            }
        }
    }
    
    private func updateButtonImages(){
        middleButton.setImage(UIImage(named: (recording ? "stop_video" : "start_video")),
                                  forState: .Normal)
    }
    
    private func changeCurrentView(changeView: UIView?){
        if let view = changeView {
            if currentView != changeView {
                currentView?.removeFromSuperview()
                view.frame = CGRect(x: 0, y: 0, width: containnerView.frame.width, height: containnerView.frame.height)
                containnerView.addSubview(view)
                currentView = view
            }
        }
    }
    
    func startPrev(){
       // cameraView?.indicator.hidden = false
        if let device = VPaiConnectionManager.shareInstance.currentConnectVPai {
            device.startPrev(){args in
            }
        }else {
           // Toast.showToast("No Connect".i18n)
        }
    }
    
    func stopPrev(){
      //  cameraView?.indicator.hidden = true
        if let device = VPaiConnectionManager.shareInstance.currentConnectVPai {
            device.stopPrev({ (ret) in
                
            })
        }
        decoderQueue.cancelAllOperations()
        self.decoderQueue.addOperationWithBlock({
         //   self.decoder.clearH264Deocder()
        });
    }
    
    
    func copyPixelBuffer()->Unmanaged<CVPixelBuffer>?{
        if !pixelBuffers.isEmpty {
            return Unmanaged.passUnretained(pixelBuffers.removeFirst())
        }else{
            return nil
        }
    }
   
    
    func onStartRec(info: StartRecInfo) {
        if !recording {
            if info.ret == 0 {
                recording = true
                // 隐藏拍照按钮
                changeMode.hidden = true
                self.isHideCountdownButton(true)

                updateButtonImages()
             //   ShortMusicPlayer.shareInstance.playSound(ShortMusicPlayeType.CAMERA_DING)
            }else{
                VPaiMediaWebSocket.shareInstance.showErrorText(info.ret)
            }
        }
        let dateFormatter = NSDateFormatter()
        dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        dateFormatter.dateFormat = "HH:mm:ss"
        let date = NSDate(timeIntervalSince1970: Double(info.recordtime))
        //cameraView?.time.hidden = false
       // cameraView?.time.text = dateFormatter.stringFromDate(date)
    }
    
    func onStopRec(info: StopRecInfo) {
        // 显示拍照按钮
        changeMode.hidden = false
        self.isHideCountdownButton(false)
        
        if recording {
            if info.ret == 0 {
                
                recording = false
                updateButtonImages()
//                ShortMusicPlayer.shareInstance.playSound(ShortMusicPlayeType.CAMERA_DING)
//                Toast.showToast("Successful,Video Stored In Sdcard".i18n)
                if let device = VPaiConnectionManager.shareInstance.currentConnectVPai{
                  //  device.remoteMediaSource.refresh()
                }
            }else {
                VPaiMediaWebSocket.shareInstance.showErrorText(info.ret)
            }
        }
       // cameraView?.time.hidden = true
    }
    
    func onStartPrev(args: CallbackArgs) {
        if args.ret != 0 || args.binary == nil {
            return;
        }
       // cameraView?.indicator.hidden = true
//        decoderQueue.addOperationWithBlock({
//            if let pixelBuffer = self.decoder.addFrame(UnsafeMutablePointer(args.binary!), bufferSize: args.binary!.count) {
//                let buffer = pixelBuffer.takeUnretainedValue()
//                CVPixelBufferLockBaseAddress(buffer, 0)
//                self.cameraView?.previewCtrl?.updateTexture(buffer)
//                
//                CVPixelBufferUnlockBaseAddress(buffer, 0)
//                self.decoder.releasePixelbuffer(buffer)
//            }
//        });
    }
    
    func onDeviceInfo(info: VPaiDeviceInfo) {
        var index = info.remainbattery/25
        if index < 0 {
            index = 0
        }else if index > 3 {
            index = 3
        }
       // cameraView?.battery.image = UIImage(named: "battery_\(index)")
    }
      /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
